<template>
	<swiper class="home-swiper" :current="activeIndex" @change="change">
		<swiper-item class="swiper-item" v-for="(item,index) in tab" :key="index">
			<list-item :list="listCatchData[index]" :load="load[index]" @loadmore="loadmore"></list-item>
		</swiper-item>
	</swiper>
</template>

<script>
	import listItem from './list-item.vue'
	export default {
		props: {
			tab: {
				type: Array,
				default () {
					return []
				}
			},
			// tab参数
			activeIndex: {
				type: Number,
				default: 0
			}
		},
		components: {
			listItem
		},
		name: "list",
		data() {
			return {
				list: [],
				listCatchData: {},
				load: {},
				pageSize: 10
			};
		},
		watch: {
			tab(newVal) {
				if (newVal.length === 0) return
				this.listCatchData = {}
				this.load = {}
				this.getList(this.activeIndex)
			}
		},
		// 组件中created 页面中用onload
		created() {
			//详情页通知首页刷新
			uni.$on('update_article', (e) => {
				//接收从like组件传来的参数e
				//如果在首页点击则不刷新
				if (e === 'follow') {
					this.listCatchData = {}
					this.load = {}
					this.getList(this.activeIndex)
				}

			})
		},
		methods: {
			// 分类请求加载
			change(e) {
				let current = e.detail.current
				this.$emit('change', current)
				// console.log(this.tab[current].name)
				//避免重复请求数据
				if (!this.listCatchData[current] || this.listCatchData[current].length === 0) {
					this.getList(current)
				}
			},
			// 数据请求
			getList(current) {
				// page loading 初始化
				if (!this.load[current]) {
					this.load[current] = {
						page: 1,
						loading: 'loading'
					}
				}
				this.$api.get_list({
					// user_id:'61309cea0d306900016d67ae',
					name: this.tab[current].name,
					page: this.load[current].page,
					pageSize: this.pageSize
				}).then((res) => {
					console.log(res)
					let result = res.data
					// this.list = result
					if (result.length === 0) {
						let oldLoad = {}
						// oldLoad = {
						// 	page:this.load[current].page,
						// 	loading:'noMore'
						// }
						oldLoad.loading = 'noMore'
						oldLoad.page = this.load[current].page
						this.$set(this.load, current, oldLoad)
						this.$forceUpdate() //强制刷新
						return
					}
					let oldList = this.listCatchData[current] || []
					oldList.push(...result)
					this.$set(this.listCatchData, current, oldList) //懒加载
				})
			},
			// 上拉加载
			loadmore() {
				// 无数据时不再请求
				if (this.load[this.activeIndex].loading === 'noMore') return
				this.load[this.activeIndex].page++
				this.getList(this.activeIndex)
				// console.log("xx")
			}
		}
	}
</script>

<style lang="scss">
	.home-swiper {
		height: 100%;

		.swiper-item {
			height: 100%;
			overflow: hidden;

		}
	}
</style>
